const merchantApi = require("../../services/merchant");
const http = require("../../utils/request");
const auth = require('../../utils/auth.js');

Page({
  data: {
    userType: "user",
    rememberPwd: false,
    merchantAccount: "",
    password: "",
    loading: false,
    imagesLoaded: false,
    phone: '',
    role: 'user',
    systemInfo: null
  },

  onLoad(options) {
    // 预加载图片
    this.preloadImages();
    
    // 检查是否有保存的商家账号
    const savedAccount = wx.getStorageSync("savedMerchantAccount");
    if (savedAccount) {
      this.setData({
        merchantAccount: savedAccount,
        rememberPwd: true,
      });
    }

    // 如果是从其他页面返回，检查是否需要切换到商家登录tab
    if (options.type === "merchant") {
      this.setData({ userType: "merchant" });
    }

    // 初始化云开发环境
    if (!wx.cloud) {
      wx.showToast({
        title: '请使用 2.2.3 或以上的基础库以使用云能力',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 检查是否已经登录
    const token = wx.getStorageSync('token');
    if (token) {
      this.redirectBasedOnRole();
    }

    // 使用新的API获取系统信息
    const appBaseInfo = wx.getAppBaseInfo();
    const systemSetting = wx.getSystemSetting();
    const deviceInfo = wx.getDeviceInfo();
    const windowInfo = wx.getWindowInfo();

    this.setData({
      systemInfo: {
        ...appBaseInfo,
        ...systemSetting,
        ...deviceInfo,
        ...windowInfo
      }
    });
  },

  // 预加载图片
  preloadImages() {
    const images = [
      '/images/logo.png',
      '/images/user_icon.png',
      '/images/merchant_icon.png',
      '/images/admin_icon.png',
      '/images/wechat.png'
    ];

    const loadPromises = images.map(src => {
      return new Promise((resolve, reject) => {
        // 检查图片是否存在
        wx.getFileSystemManager().access({
          path: src,
          success: () => {
            wx.getImageInfo({
              src: src,
              success: resolve,
              fail: (err) => {
                console.warn(`图片加载失败: ${src}`, err);
                resolve(); // 即使加载失败也继续执行
              }
            });
          },
          fail: () => {
            console.warn(`图片不存在: ${src}`);
            resolve(); // 图片不存在也继续执行
          }
        });
      });
    });

    Promise.all(loadPromises)
      .then(() => {
        this.setData({ imagesLoaded: true });
      })
      .catch(error => {
        console.error('图片预加载失败：', error);
        this.setData({ imagesLoaded: true }); // 即使失败也设置加载完成
      });
  },

  selectUserType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      userType: type,
      merchantAccount: "",
      password: "",
    });
  },

  async handleWechatLogin() {
    // 防止重复点击
    if (this.data.loading) {
      return;
    }

    let loadingShown = false;
    try {
      this.setData({ loading: true });
      wx.showLoading({ 
        title: '登录中...',
        mask: true  // 防止用户触摸穿透
      });
      loadingShown = true;

      // 1. 获取用户信息授权
      const userProfile = await wx.getUserProfile({
        desc: '用于完善用户资料'
      });
      console.log('用户信息获取成功', userProfile);

      // 2. 获取登录凭证
      const { code } = await wx.login();
      if (!code) {
        throw new Error('获取登录凭证失败');
      }
      console.log('登录凭证获取成功', code);

      // 3. 调用云函数登录
      const { result } = await wx.cloud.callFunction({
        name: 'userLogin',
        data: {
          code,
          userInfo: {
            nickName: userProfile.userInfo.nickName,
            avatarUrl: userProfile.userInfo.avatarUrl,
            gender: userProfile.userInfo.gender,
            role: 'user'
          }
        }
      });

      console.log('云函数调用结果', result);

      // 4. 验证返回结果
      if (!result || result.code !== 0) {
        throw new Error(result?.message || '登录失败，请重试');
      }

      // 5. 保存用户信息
      wx.setStorageSync('token', result.data.token);
      wx.setStorageSync('userId', result.data.userId);
      wx.setStorageSync('userInfo', {
        ...userProfile.userInfo,
        role: 'user'
      });
      wx.setStorageSync('role', 'user');

      // 6. 显示成功提示并跳转
      if (loadingShown) {
        wx.hideLoading();
        loadingShown = false;
      }

      wx.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500
      });

      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/menu/menu'
        });
      }, 1500);

    } catch (error) {
      console.error('登录失败', error);
      
      // 确保loading被关闭
      if (loadingShown) {
        wx.hideLoading();
        loadingShown = false;
      }

      // 显示错误信息
      wx.showToast({
        title: error.message || '登录失败，请重试',
        icon: 'none',
        duration: 2000
      });

    } finally {
      // 重置loading状态
      this.setData({ loading: false });
      
      // 以防万一，再次确保loading被关闭
      if (loadingShown) {
        wx.hideLoading();
      }
    }
  },

  redirectBasedOnRole: function() {
    const role = wx.getStorageSync('role');
    switch (role) {
      case 'user':
        wx.switchTab({
          url: '/pages/menu/menu'
        });
        break;
      case 'merchant':
        wx.redirectTo({
          url: '/pages/merchant/dashboard/dashboard'
        });
        break;
      case 'admin':
        wx.redirectTo({
          url: '/pages/admin/dashboard/dashboard'
        });
        break;
      default:
        wx.switchTab({
          url: '/pages/menu/menu'
        });
    }
  },

  handleGuestLogin() {
    wx.showLoading({ title: "进入中..." });
    setTimeout(() => {
      wx.hideLoading();
      wx.navigateBack();
    }, 1000);
  },

  // 商家登录相关
  inputMerchantAccount(e) {
    this.setData({ merchantAccount: e.detail.value });
  },

  inputPassword(e) {
    this.setData({ password: e.detail.value });
  },

  toggleRememberPwd() {
    this.setData({ rememberPwd: !this.data.rememberPwd });
  },

  handleForgetPwd() {
    wx.navigateTo({
      url: "/pages/merchant/forget-pwd",
    });
  },

  handleMerchantRegister() {
    wx.navigateTo({
      url: "/pages/merchant/register",
    });
  },

  // 管理员登录相关
  inputAdminAccount(e) {
    this.setData({ adminAccount: e.detail.value });
  },

  handleLogin() {
    const { phone, password, role } = this.data;

    // 输入验证
    if (!phone || !password) {
      wx.showToast({
        title: '请输入手机号和密码',
        icon: 'none'
      });
      return;
    }

    // 手机号格式验证
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    // 调用登录云函数
    wx.cloud.callFunction({
      name: 'userLogin',
      data: {
        phone,
        password,
        role
      }
    }).then(res => {
      if (res.result.code === 0) {
        // 保存登录状态和用户信息
        auth.saveLoginStatus(res.result.token);
        auth.saveUserInfo({
          ...res.result.userInfo,
          role: role
        });

        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });

        // 根据角色跳转到不同页面
        setTimeout(() => {
          if (role === 'admin') {
            wx.redirectTo({
              url: '/pages/admin/index'
            });
          } else if (role === 'merchant') {
            wx.redirectTo({
              url: '/pages/merchant/index'
            });
          } else {
            wx.switchTab({
              url: '/pages/menu/menu'
            });
          }
        }, 1500);
      } else {
        wx.showToast({
          title: res.result.message || '登录失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('登录失败:', err);
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    }).finally(() => {
      this.setData({ loading: false });
    });
  },

  goToRegister() {
    wx.navigateTo({
      url: `/pages/register/register?role=${this.data.role}`
    });
  },

  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  onRoleChange(e) {
    this.setData({
      role: e.detail.value
    });
  },
});
